﻿using IdentityModel;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using System.Security.Claims;

namespace MyIDP.Permission
{
    public class MyProfileService : IProfileService
    {
        MyUserManager userManager;
        public MyProfileService(MyUserManager manager)
        {
            userManager = manager;
        }

        public Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var user = userManager.FindByIdAsync(context.Subject.GetSubjectId()).Result;
            Console.WriteLine("获取profile信息");
            if (user != null)
            {
                var claims = userManager.GetClaimsAsync(user).Result;
                Console.WriteLine("获取user claims信息");
                context.IssuedClaims.AddRange(claims);
                var role = userManager.GetRolesAsync(user).Result.Select(t => new Claim(JwtClaimTypes.Role, t));
                context.IssuedClaims.AddRange(role);
                context.IssuedClaims.Add(new Claim("account", user.UserName));
                Console.WriteLine($"-------------\r\n{string.Join("\r\n", claims.Select(t => $"{t.Type}:{t.Value}"))}");
            }

            return Task.CompletedTask;
        }

        public Task IsActiveAsync(IsActiveContext context)
        {
            //context.IsActive = true;
            return Task.Run(() => { context.IsActive = true; });
        }
    }
}
